package com.example.module_motocircle.motocircledetail

import android.graphics.Rect
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.alibaba.android.arouter.facade.annotation.Route
import com.example.lib_common.Router
import com.example.lib_common.base.BaseToolBarActivity
import com.example.lib_common.base.state.Failed
import com.example.lib_common.base.state.Success
import com.example.lib_common.base.state.UILoader
import com.example.lib_common.base.state.UIState
import com.example.lib_common.base.utils.ToastUtils
import com.example.lib_common.dp
import com.example.lib_common.observeWithLifecycle
import com.example.module_motocircle.R
import com.example.module_motocircle.adpater.EndlessRecyclerOnScrollListener
import com.example.module_motocircle.adpater.PostDetailsAdapter
import com.example.module_motocircle.databinding.ActivityMotocircleDetailBinding
import com.example.module_motocircle.databinding.LayoutPostDetailsContentBinding
import com.example.module_motocircle.model.CommentRecord
import com.example.module_motocircle.motocircle.MotocircleViewModel
import dagger.hilt.android.AndroidEntryPoint
import java.util.Collections.addAll

@Route(path = Router.Ui.MotocircleDetailActivity)
@AndroidEntryPoint
class MotocircleDetailActivity : BaseToolBarActivity<MotocircleViewModel,ActivityMotocircleDetailBinding>() {
    override val mLayoutResId: Int
        get() = R.layout.activity_motocircle_detail
    private val mViewModel: MotocircleViewModel by viewModels()
    private lateinit var mUiLoader: UILoader
    private lateinit var mContentBinding: LayoutPostDetailsContentBinding
    private val mPostDetailsAdapter: PostDetailsAdapter by lazy {
        PostDetailsAdapter()
    }
    override fun initView() {
        super.initView()
        initToolbar()
        initUILoader()
        initAdapter()
    }


    override fun initData() {
        mContentBinding.post = mViewModel.currentPost
        mViewModel.initOrRefreshPostDetailsPageData()
    }

    override fun initListener() {
        //数据初始化状态
        mViewModel.initState.observeWithLifecycle(this) {
            when (it) {
                is Success -> {
                    setPageData()
                }

                is Failed -> {
                    ToastUtils.showShort(this, it.message)
                    mUiLoader.updateState(UIState.EMPTY)
                }
                else ->{}
            }
        }
    }
    //设置页面数据
    private fun setPageData() {
        val totalCommentsSize = mViewModel.currentPost?.comment_number ?: 0
        mContentBinding.lHeader.tvCommentsNum.text = String.format("%d 条评论", totalCommentsSize)
        mContentBinding.post = mViewModel.currentPost
        mPostDetailsAdapter.setPostInfo(mViewModel.currentPost, totalCommentsSize, mViewModel.get1stPageCommentsNum())
        mPostDetailsAdapter.setCommentsNewData(mutableListOf<CommentRecord>().apply { addAll(mViewModel.formatCommentsList) })
        mUiLoader.updateState(UIState.SUCCESS)
    }
    private fun initToolbar(){
        mBinding.appbar.toolbarTitle.text = getString(com.example.lib_common.R.string.string_post_details)
        mToolbar.inflateMenu(R.menu.single_menu)
//        mToolbar.setOnMenuItemClickListener {
//            if (it.itemId == R.id.action)
//        }
    }
    private fun initAdapter() {
        (mContentBinding.rvPostDetails.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
        mContentBinding.rvPostDetails.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
        mContentBinding.rvPostDetails.addItemDecoration(object : RecyclerView.ItemDecoration() {
            override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
                val position = parent.getChildLayoutPosition(view)
                if (position == 0) {
                    outRect.top = 1.dp
                    outRect.bottom = 10.dp
                } else if (position == 1) {
                    outRect.bottom = 1.dp
                }
            }
        })
//        mContentBinding.rvPostDetails.addOnScrollListener(object : RecyclerView.OnScrollListener() {
//            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
//                val position = (recyclerView.layoutManager as LinearLayoutManager).findFirstVisibleItemPosition()
//                if (position < 1) {
//                    mContentBinding.lHeader.root.visibility = View.GONE
//                } else {
//                    mContentBinding.lHeader.root.visibility = View.VISIBLE
//                }
//            }
//        })
        mContentBinding.rvPostDetails.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
        mContentBinding.rvPostDetails.adapter = mPostDetailsAdapter

        mContentBinding.rvPostDetails.addOnScrollListener(object : EndlessRecyclerOnScrollListener() {
            override fun onLoadMore() {
//                if (!mClickLoadMore) {
//                    mViewModel.loadCommentsByPage(postId)
//                }
            }
        })
    }
    private fun initUILoader() {
        mContentBinding = DataBindingUtil.inflate(
            LayoutInflater.from(this),
            R.layout.layout_post_details_content,
            null,
            false
        )
        mUiLoader = object : UILoader(this) {
            override fun loadSuccessView(container: ViewGroup?): View {
                return mContentBinding.root
            }
        }.apply { updateState(UIState.LOADING) }

        mBinding.layoutContent.addView(mUiLoader)
    }

}